package com.shjl.kechuang.utils;

import com.shjl.kechuang.domain.pojo.KySpecSme;
import com.shjl.kechuang.mapper.KySpecSmeMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @title: WordReader
 * @author: wywang
 * @date: 2025/04/10
 * @description: 读取 .doc 和 .docx 文件并解析内容
 **/
@Slf4j
@Component
public class WordReader {

    @Autowired
    private KySpecSmeMapper kySpecSmeMapper;

    public void readWord(String filename, KySpecSme kySpecSme) {
        File file = new File(filename);
        if (!file.exists()) {
            log.error("文件不存在: {}", filename);
            throw new RuntimeException("文件不存在");
        }

        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            String text;

            // 判断文件类型
            if (filename.toLowerCase().endsWith(".doc")) {
                // 处理 .doc 文件
                HWPFDocument document = new HWPFDocument(fileInputStream);
                WordExtractor extractor = new WordExtractor(document);
                text = extractor.getText();
            } else if (filename.toLowerCase().endsWith(".docx")) {
                // 处理 .docx 文件
                XWPFDocument document = new XWPFDocument(fileInputStream);
                XWPFWordExtractor extractor = new XWPFWordExtractor(document);
                text = extractor.getText();
            } else {
                log.error("不支持的文件类型: {}", filename);
                throw new RuntimeException("不支持的文件类型");
            }

            // 解析文本内容
            parseText(text, kySpecSme);

        } catch (IOException e) {
            log.error("读取文件时发生异常: {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    private void parseText(String text, KySpecSme kySpecSme) {
        String[] lines = text.split("\n");
        for (String line : lines) {
            if (line.contains("附件") || line.contains("名单") || line.contains("序号")) {
                continue;
            }

            // 去掉行首的序号和空格
            String cleanedLine = line.replaceAll("^(\\d+([,\\d]*)?)\\s+", "") // 去掉序号
                    .replaceAll("\\s+", " ")               // 合并多余空格
                    .trim();

            String[] split = cleanedLine.split(" ");
            if (split.length == 2) {
                String companies = split[0].trim();
                String area = split[1].trim();

                kySpecSme.setCompanies(companies);
                kySpecSme.setArea(area);
                kySpecSmeMapper.insert(kySpecSme);
            }
        }
    }
}